package com.frxuexi.repair.view

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.RepairBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.RequestType
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.DateTimeUtils
import com.frxuexi.repair.RepairIntent
import com.frxuexi.repair.RepairViewModel
import com.frxuexi.repair.adapter.RepairImageAdapter
import com.frxuexi.repair.databinding.ActivityRepairEditBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/repair/RepairEditActivity")
@AndroidEntryPoint
class RepairEditActivity : BaseActivity<ActivityRepairEditBinding, RepairIntent, RepairViewModel>() {
    override val binding: ActivityRepairEditBinding by lazy { ActivityRepairEditBinding.inflate(layoutInflater) }
    override val vm: RepairViewModel by viewModels<RepairViewModel>()
    var loc="A区办公室"
    val repairImageAdapter by lazy { RepairImageAdapter() }
    lateinit var adapter: ArrayAdapter<String>
    val locs= mutableListOf<String>("A区办公室","B区办公室")
    val imgs= mutableListOf<String>()
    @JvmField
    @Autowired
    var id:Int?=-1

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.ADD->{
                                ToastUtils.showLong("报修成功")
                                finish()
                            }
                            RequestType.UPDATE->{
                                ToastUtils.showLong("修改成功")
                                finish()
                            }
                            RequestType.DEFAULT->{
                                val item = it.data as RepairBeanItem
                                binding.repairEditName.setText(item.repairName)
                                binding.repairEditPhone.setText(item.contactMethod)
                                binding.repairEditDesc.setText(item.faultDescription)
                                if(!locs.contains(item.repairLocation)){
                                    locs.add(0,item.repairLocation)
                                    adapter = ArrayAdapter(this@RepairEditActivity, android.R.layout.simple_spinner_item, locs)
                                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                    binding.repairEditLoc.adapter=adapter
                                }
                                if(item.faultPhotos.isNotEmpty()) {
                                    if(item.faultPhotos.contains(",")) {
                                        imgs.addAll(item.faultPhotos.split(","))
                                    }
                                    else{
                                        imgs.add(item.faultPhotos)
                                    }
                                    repairImageAdapter.addData(imgs)
                                    repairImageAdapter.notifyDataSetChanged()
                                }
                            }
                            RequestType.UPLOAD->{
                                val data = it.data as String
                                val name = data.split(":")[1]
                                imgs.add( "http://10.161.9.80:2209/images/repair/${SPUtils.getInstance().getInt(Const.UID)}/${name}")
                            }

                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        if(id!=-1){//修改
            vm.sendIntent(RepairIntent.getRepairById(id!!))
        }

        adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, locs)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.repairEditLoc.adapter=adapter
        binding.repairEditLoc.onItemSelectedListener=object :OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                loc=locs.get(position)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }

        binding.repairEditRv.apply {
            this.adapter=repairImageAdapter
            layoutManager= GridLayoutManager(this@RepairEditActivity,3)
        }

        binding.repairEditAdd.setOnClickListener {
            if(imgs.size==4){
                ToastUtils.showLong("图片已达上限")
            }else {
                PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
            }
        }
        val uname = SPUtils.getInstance().getString(Const.UNAME)
        binding.repairEditName.setText(uname)

        binding.repairCommit.setOnClickListener {
            val phone = binding.repairEditPhone.text.toString()
            val desc = binding.repairEditDesc.text.toString()
            val name = binding.repairEditName.text.toString()
            val item = RepairBeanItem(
                phone,
                desc,
                imgs.joinToString(","),
                null,
                "WX${DateTimeUtils.getDateTimeNum()}",
                "待处理",
                loc,
                name,
                DateTimeUtils.getDateTime(System.currentTimeMillis()),
                SPUtils.getInstance().getInt(Const.UID)
            )
            if(id!=-1){//修改
                item.id=id
                vm.sendIntent(RepairIntent.updateRepair(id!!, item))
            }else {
                vm.sendIntent(RepairIntent.addRepair(item))
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==PictureSelector.SELECT_REQUEST_CODE && resultCode== RESULT_OK){
            val bean =
                data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)
            val path=bean?.path!!
            repairImageAdapter.addData(path)
            repairImageAdapter.notifyDataSetChanged()

            Log.i("lr",path)
            val split = path.split(Regex("[/]"))
            val fileName = split.get(split.lastIndex)
            vm.sendIntent(RepairIntent.upload(fileName,path))
        }
    }

}